'use strict';

const { Service } = require('egg');
const https = require('https');

class TokenService extends Service {
  getToken(force) {
    const { ctx } = this;
    if (!ctx.app.token || ctx.app.expire <= new Date() || force) {
      return new Promise((resolve, reject) => {
        https.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9410f8d32e6bffd4&secret=dec8bb7d24f5aad1b761d5eb4acfba0c', res => {
          if (res.statusCode === 200) {
            let data = '';
            res.on('data', chunk => { data += chunk; });
            res.on('end', () => {
              const dt = JSON.parse(data);
              if (dt.access_token) {
                ctx.app.token = dt.access_token;
                ctx.app.expire = new Date();
                ctx.app.expire.setSeconds(ctx.app.expire.getSeconds() + dt.expires_in);
                resolve(ctx.app.token);
              } else {
                reject(new Error(dt.errmsg));
              }
            });
          } else {
            reject(new Error('HTTP ' + res.statusCode));
          }
        }).end();
      });
    }

    return new Promise(resolve => resolve(ctx.app.token));
  }
}

module.exports = TokenService;
